﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using PPIDesktopClient.General;
using System.IO;
using VMind.Global;
using PPIDesktopClient.Entities.Xml;

namespace PPIDesktopClient.General
{
    public class XMLHelper
    {
        public static void CreateXML(string fileName)
        {
            XmlDocument _Document = new XmlDocument();
            XmlNode _FoldersNode = null;
            if (File.Exists(fileName))
            {
                try
                {
                    _Document.Load(fileName);
                }
                catch (Exception ex)
                {
                    XmlNode _DocumentNode = _Document.CreateXmlDeclaration("1.0", "UTF-8", null);
                    _Document.AppendChild(_DocumentNode);

                    _FoldersNode = _Document.CreateElement("Folders");
                    _Document.AppendChild(_FoldersNode);
                }
                
            }
            if (_Document.ChildNodes.Count == 0)
            {
                XmlNode _DocumentNode = _Document.CreateXmlDeclaration("1.0", "UTF-8", null);
                _Document.AppendChild(_DocumentNode);

                _FoldersNode = _Document.CreateElement("Folders");
                _Document.AppendChild(_FoldersNode);
            }
            else
            {
                _FoldersNode = GetFoldersNode(_Document);
            }
            //CleanNodes(_Document);
            AddFolders(_Document, _FoldersNode);
            _Document.Save(fileName);
        }

        private static XmlNode GetFoldersNode(XmlDocument _Document)
        {
            XmlNode _FoldersNode = _Document.ChildNodes[1]; //Folders Node
            return _FoldersNode;
        }

        private static void AddFolders(XmlDocument document, XmlNode foldersNode)
        {
            string _FolderLookUp = Constants.K_OutboxPath;
            DirectoryInfo _DirectorOutbox = new DirectoryInfo(_FolderLookUp);
            DirectoryInfo[] _OutboxFolders = _DirectorOutbox.GetDirectories();
            XmlNodeList _AllreadyFolders = document.SelectNodes(@"Folders/Folder");
            XmlNode _FolderNodeDocument = null;
            bool AddFolder = true;

            foreach (DirectoryInfo Folder in _OutboxFolders)
            {
                _FolderNodeDocument = document.SelectSingleNode(@"Folders/Folder[@ID='" + Folder.Name + "']");
                if (_FolderNodeDocument == null)
                {
                    XmlNode _FolderNode = document.CreateElement("Folder");
                    XmlAttribute _IdAttribute = document.CreateAttribute("ID");
                    _IdAttribute.Value = Folder.Name;
                    _FolderNode.Attributes.Append(_IdAttribute);

                    XmlNode _DataUploadedNode = document.CreateElement("Data_Uploaded");
                    _DataUploadedNode.AppendChild(document.CreateTextNode(false.ToString()));
                    _FolderNode.AppendChild(_DataUploadedNode);

                    XmlNode _DateFinishedDataNode = document.CreateElement("Data_Finished");
                    _DateFinishedDataNode.AppendChild(document.CreateTextNode(""));
                    _FolderNode.AppendChild(_DateFinishedDataNode);


                    XmlNode _ImagesUploadedNode = document.CreateElement("Images_Uploaded");
                    _ImagesUploadedNode.AppendChild(document.CreateTextNode(false.ToString()));
                    _FolderNode.AppendChild(_ImagesUploadedNode);

                    XmlNode _DateFinishedImageNode = document.CreateElement("Images_Finished");
                    _DateFinishedImageNode.AppendChild(document.CreateTextNode(""));
                    _FolderNode.AppendChild(_DateFinishedImageNode);

                    XmlNode _Path = document.CreateElement("Path");
                    _Path.AppendChild(document.CreateTextNode(Folder.FullName));
                    _FolderNode.AppendChild(_Path);

                    XmlNode _ConnectionString = document.CreateElement("ConnectionString");
                    _ConnectionString.AppendChild(document.CreateTextNode(DirHelper.GetSdfPath(Folder.FullName)));
                    _FolderNode.AppendChild(_ConnectionString);

                    XmlNode _Opened = document.CreateElement("Open");
                    _Opened.AppendChild(document.CreateTextNode(false.ToString()));
                    _FolderNode.AppendChild(_Opened);


                    foldersNode.AppendChild(_FolderNode);
                }
            }
        }

        private static void CleanNodes(XmlDocument document)
        {
            XmlNodeList _AllreadyFolders = document.ChildNodes[1].ChildNodes;
            foreach (XmlNode AllreadyFolder in _AllreadyFolders)
            {
                if (!Directory.Exists(AllreadyFolder["Path"].InnerText))
                {
                    AllreadyFolder.ParentNode.RemoveChild(AllreadyFolder);
                }
            }
        }

        public static string GetNextFolder(string fileName)
        {
            try
            {
                XmlDocument _Document = new XmlDocument();
                _Document.Load(fileName);
                XmlNodeList _ActualNode = GetNextNodesFiltered(_Document);
                string ReturnConnectionString = "";
                if (_ActualNode.Count > 0)
                {
                    ReturnConnectionString = _ActualNode[0]["ConnectionString"].InnerText;
                }
                return ReturnConnectionString;
            }
            catch (Exception)
            {

                throw;
            }
        }

        private static XmlNodeList GetNextNodesByFolder(XmlDocument document, string actualFolder)
        {
            XmlNodeList _ActualNode = document.SelectNodes(@"//Folder[@ID='" + actualFolder + "']");
            return _ActualNode;
        }
        private static XmlNodeList GetNextNodesFiltered(XmlDocument document)
        {
            XmlNodeList _ActualNode = document.SelectNodes(@"//Folder[Data_Uploaded='" + false.ToString() + "']");
            return _ActualNode;
        }

        private static XmlNodeList GetNextNodesFilteredToUpload(XmlDocument document)
        {
            XmlNodeList _ActualNode = document.SelectNodes(@"//Folder[Data_Uploaded='" + false.ToString() + "' or Images_Uploaded='" + false.ToString() + "']");
            return _ActualNode;
        }

        private static XmlNodeList GetNextImageNodes(XmlDocument document)
        {
            XmlNodeList _ActualNode = document.SelectNodes(@"//Folder[Data_Uploaded='" + true.ToString() + "'  and Images_Uploaded='" + false.ToString() + "']");
            return _ActualNode;

        }

        public static bool IsDatabaseOpened(XmlDocument document, string folderID)
        {
            XmlNodeList _ActualNode = document.SelectNodes(@"//Folder[@ID='" + folderID + "']");
            return ConvertHelper.Tobool(_ActualNode[0]["Open"].InnerText);
        }

        public static bool HastNextImageNode(string fileName)
        {
            XmlDocument _Document = new XmlDocument();
            _Document.Load(fileName);
            XmlNodeList _NodeList = GetNextImageNodes(_Document);
            return (_NodeList.Count > 0);
        }

        public static bool HasNextFolder(string fileName)
        {
            XmlDocument _Document = new XmlDocument();
            _Document.Load(fileName);
            XmlNodeList _NodeList = GetNextNodesFiltered(_Document);
            return (_NodeList.Count > 0);
        }

        public static void UpdateFolderNode(string fileName, string id)
        {
            XmlDocument _Document = new XmlDocument();
            _Document.Load(fileName);
            XmlNode _UpdateNode = _Document.SelectSingleNode(@"//Folder[@ID='" + id + "']");
            _UpdateNode["Data_Uploaded"].InnerText = true.ToString();
            _UpdateNode["Data_Finished"].InnerText = DateTime.Now.ToString();
            _Document.Save(fileName);
        }

        public static void UpdateImageNode(string fileName, string id)
        {
            XmlDocument _Document = new XmlDocument();
            _Document.Load(fileName);
            XmlNode _UpdateNode = _Document.SelectSingleNode(@"//Folder[@ID='" + id + "']");
            _UpdateNode["Images_Uploaded"].InnerText = true.ToString();
            _UpdateNode["Images_Finished"].InnerText = DateTime.Now.ToString();
            _Document.Save(fileName);
        }

        public static void UpdateOpenedDatabase(string fileName, string id)
        {
            XmlDocument _Document = new XmlDocument();
            _Document.Load(fileName);
            XmlNode _UpdateNode = GetFolderByID(_Document, id);
            _UpdateNode["Open"].InnerText = true.ToString();
            _Document.Save(fileName);
        }

        public static string GetFirstFolder(string fileName)
        {
            XmlDocument _Document = new XmlDocument();
            _Document.Load(fileName);
            return _Document.ChildNodes[1].ChildNodes[0]["ConnectionString"].InnerText;
        }

        public static string GetNextImageNode(string fileName)
        {
            XmlDocument _Document = new XmlDocument();
            _Document.Load(fileName);
            XmlNodeList _NodeList = GetNextImageNodes(_Document);
            return _NodeList[0]["ConnectionString"].InnerText;
        }

        private static XmlNode GetFolderByID(XmlDocument document, string id)
        {
            XmlNodeList _NodeList = GetNextNodesFiltered(document);
            return _NodeList[0];
        }
        private static XmlNode GetImageByID(XmlDocument document, string id)
        {
            XmlNodeList _NodeList = GetNextImageNodes(document);
            return _NodeList[0];
        }

        public static void CleanNode(string fileName, string idFolder)
        {
            XmlDocument _Document = new XmlDocument();
            _Document.Load(fileName);
            XmlNode _FoldersNode = GetFoldersNode(_Document);
            XmlNode _ActualNode = _FoldersNode.SelectSingleNode(@"//Folder[@ID='" + idFolder + "']");
            _ActualNode.ParentNode.RemoveChild(_ActualNode);
        }

        public static List<EOutbox> GetDatabases(string fileName)
        {
            XmlDocument _Document = new XmlDocument();
            _Document.Load(fileName);
            XmlNode _FoldersNode = GetFoldersNode(_Document);
            List<EOutbox> m_OutboxFolders = new List<EOutbox>();
            EOutbox m_Folder;
            foreach (XmlNode  c in _FoldersNode.ChildNodes)
            {
                m_Folder = ParseNode(c); 
                m_OutboxFolders.Add(m_Folder);
            }
            return m_OutboxFolders;
        }

        private static EOutbox ParseNode(XmlNode c)
        {
            EOutbox m_Folder;
            m_Folder = new EOutbox();
            m_Folder.ConnectionString = c["ConnectionString"].InnerText;
            m_Folder.MobilePath = c["Path"].InnerText;
            m_Folder.IsOpenedDatabase = ConvertHelper.Tobool(c["Open"].InnerText);
            m_Folder.IsDataUploaded = ConvertHelper.Tobool(c["Data_Uploaded"].InnerText);
            m_Folder.IsImagesUploaded = ConvertHelper.Tobool(c["Images_Uploaded"].InnerText);
            m_Folder.FinishedDate = ConvertHelper.ToDateTime(c["Data_Finished"].InnerText);
            m_Folder.Id = c.Attributes["ID"].Value;

            return m_Folder;
        }

        public static EOutbox GetDatabase(string filename, string connectionString)
        {
            XmlDocument _Document = new XmlDocument();
            _Document.Load(filename);

            XmlNode _ActualNode = _Document.SelectSingleNode(@"//Folder[ConnectionString='" + connectionString + "']");
            return ParseNode(_ActualNode);
        }
        public static List<EOutbox> GetDatabasesToUpload(string filename)
        {
            XmlDocument _Document = new XmlDocument();
            _Document.Load(filename);
            XmlNodeList _FoldersNode = GetNextNodesFilteredToUpload(_Document);
            List<EOutbox> m_OutboxFolders = new List<EOutbox>();
            EOutbox m_Folder;
            foreach (XmlNode c in _FoldersNode)
            {
                m_Folder = ParseNode(c);
                m_OutboxFolders.Add(m_Folder);
            }
            return m_OutboxFolders;
        }

    }

}
